package com.nian.search.solr.service.impl;

import com.nian.search.solr.dao.SolrItemRepository;
import com.nian.search.solr.model.SolrItem;
import com.nian.search.solr.service.ISolrItemService;
import com.nian.search.solr.vo.SolrItemVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.SolrParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * 用途：
 * 开发：zhangmj
 * 日期：2020/4/14 0014 11:46
 */
@Service
public class SolrItemServiceImpl implements ISolrItemService {

    @Autowired
    private SolrItemRepository solrItemRepository;

    @Autowired
    private SolrClient solrClient;

    @Override
    public SolrItem findById(String id) {
        if (StringUtils.isNotEmpty(id)) {
            return solrItemRepository.findById(id).orElse(null);
        }
        return null;
    }

    @Override
    public SolrItem save(SolrItem model) {
        if (model != null) {
            return solrItemRepository.save(model);
        }
        return model;
    }

    @Override
    public Iterable<SolrItem> saveAll(List<SolrItem> list) {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        return solrItemRepository.saveAll(list);
    }

    @Override
    public void deleteById(String id) {
        if (StringUtils.isNotEmpty(id)) {
            solrItemRepository.deleteById(id);
        }
    }

    @Override
    public Page<SolrItem> listPage(Pageable page) {
        return solrItemRepository.findAll(page);
    }

    @Override
    public Iterable<SolrItem> findAll() {
        return solrItemRepository.findAll();
    }

    @Override
    public Page<SolrItem> search(SolrItemVO query) {
        Integer pageNum = query.getPage().getPageNum();
        Integer pageSize = query.getPage().getPageSize();
        PageRequest page = PageRequest.of(pageNum, pageSize);
        return solrItemRepository.findByQueryAnnotation(query.getTitle(), page);
    }
}
